package com.whmskj.xjlhbc.mobile.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.whmskj.xjlhbc.core.AjaxResult;
import com.whmskj.xjlhbc.domain.PasswordAuth;
import com.whmskj.xjlhbc.dto.LoginDto;
import com.whmskj.xjlhbc.mapper.PasswordAuthMapper;
import com.whmskj.xjlhbc.service.IPersonnelManagementDataSheetsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@Tag(name="登录",description = "登录")
public class LoginController {

    @Autowired
    private PasswordAuthMapper passwordAuthMapper;

    @Autowired
    private IPersonnelManagementDataSheetsService personnelManagementDataSheetsService;

    @PostMapping("/login")
    @Operation(description = "账号密码登录")
    public AjaxResult login(@RequestBody LoginDto param){
        String username = param.getUsername();
        String password = param.getPassword();
        LambdaQueryWrapper<PasswordAuth> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PasswordAuth::getUsername, username);
        PasswordAuth passwordAuth = passwordAuthMapper.selectOne(wrapper);
        if(Objects.isNull(passwordAuth)){
            return AjaxResult.error("账号不存在");
        }
        String pwd = passwordAuth.getPassword();
        String str = pwd.split("#")[0];
        String str1 = pwd.split("#")[1];
        String passwordMd5 = MD5.create().digestHex(password);
        String digest = MD5.create().digestHex(passwordMd5+str1);
        if(!str.equals(digest)){
            return AjaxResult.error("账号密码错误");
        }
        StpUtil.login(passwordAuthMapper.getNewUserId(passwordAuth.getUserId()));
        String token = StpUtil.getTokenValue();
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        return AjaxResult.success(map);
    }

    @PostMapping("/getLoginInfo")
    @Operation(description = "获取登录信息")
    public AjaxResult getLoginInfo(){
        return AjaxResult.success(personnelManagementDataSheetsService.getByLoginUserId());
    }

}
